/**
 * 默认配置
 */
const config = {
  APIURL: "",
  OSSURL: "",
};
/**
 * 本地存储使用
 * @param {*} String key
 * @param {*} Object [val]
 */
function useStorage(key, val = false) {
  let data = JSON.parse(localStorage.getItem(key) || "{}");
  return val
    ? localStorage.setItem(key, JSON.stringify({ ...data, ...val }))
    : data;
}
/**
 * 获取用户信息
 * @param {*} Object
 */
function useProfile() {
  let { access_token, expire, ...uerInfo } = useStorage("profile");
  if (access_token && expire > Date.now()) {
    return uerInfo;
  } else {
    return { err: 401, msg: "未登录或登录过期" };
  }
}

/**
 * 统一网络接口处理
 * @param {*} path
 * @param {*} params
 */
const _apiFetch = (path, params) => {};

/**
 * 统一处理图片样式
 * @param {*} url
 * @returns
 */
const _useImage = ({ url, size }) => {
  return `//cdn.why.cn/path/${url}?${size}`;
};
/**
 * OSS单点登录服务
 * @param {*} Object.scope
 * @param {*} Object.redirect
 * @returns
 */
const _ssoLogin = ({ scope = "", redirect }) => {
  let dialog = document.createElement("dialog"),
    iframe = document.createElement("iframe");
  dialog.id = "ssoLogin";
  iframe.id = "mapPage";
  iframe.width = "360px";
  iframe.height = "720px";
  iframe.frameborder = 0;
  iframe.src = `//www.jsggwhy.cn/index.php/Home/User/login.html?scope=${scope}&redirect=${redirect}`;
  dialog.appendChild(iframe);
  document.body.appendChild(dialog);
  dialog.showModal();
  return new Promise((resolve, reject) => {
    dialog.addEventListener("close", () => {
      resolve();
    });
  });
};
/**
 * 腾讯地图坐标拾取器
 * @param {*} Object deploy
 */
const _mapPicker = ({
  key,
  coord = "",
  coordtype = 5,
  referer,
  search = 1,
}) => {
  let iframe = document.createElement("iframe"),
    dialog = document.createElement("dialog");
  iframe.id = "mapPage";
  iframe.width = "360px";
  iframe.height = "720px";
  iframe.frameborder = 0;
  iframe.src = `https://apis.map.qq.com/tools/locpicker?policy=1&mapdraggable=1&type=1&coord=${coord}&key=${key}&coordtype=${coordtype}&referer=jsggwhy`;
  dialog.appendChild(iframe);
  document.body.appendChild(dialog);
  dialog.showModal();
  return new Promise((resolve, reject) => {
    window.addEventListener(
      "message",
      function ({ data }) {
        if (data && data.module == "locationPicker") {
          resolve(data);
          dialog.remove();
        }
      },
      false
    );
  });
};
/**
 * 导出方法
 */
export default function (deploy = {}) {
  // 全局配置
  const configed = { ...config, ...deploy };
  // 局部配置
  const apiFetch = (ini) => _apiFetch({ ...configed, ...ini });
  const useImage = (url, size = "small") =>
    _useImage({ ...configed, ...{ url, size } });
  const mapPicker = (ini) => _mapPicker({ ...configed, ...ini });
  const ssoLogin = (ini) => _ssoLogin({ ...configed, ...ini });

  // 统一导出
  return {
    apiFetch,
    ssoLogin,
    mapPicker,
    useImage,
  };
}
